<template>
  <div class="order-form-container">
    <!-- 3D模拟器：修复props传递，移除冗余的:config，仅保留事件监听 -->
    <el-card shadow="never" class="pallet-card">
      <div class="card-header">
        <span class="card-title">产品3D参考</span>
      </div>
      <pallet-simulator 
        ref="palletSimulator" 
        @config-update="handlePalletUpdate" 
      />
    </el-card>
 
    <!-- 订单表单：保持结构不变，优化数据联动 -->
    <el-card shadow="never" class="form-card">
      <el-form :model="form" :rules="rules" label-position="top" ref="orderFormRef">
        <!-- 送货信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="期望收货日期" prop="deliveryDate">
              <el-date-picker 
                v-model="form.deliveryDate"   
                type="date" 
                placeholder="选择日期"
                :disabled-date="disabledPastDates" 
                style="width: 100%" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="送货时间" prop="deliveryHour">
              <el-select 
                v-model="form.deliveryHour"   
                placeholder="选择小时 (7:00-18:00)" 
                style="width: 100%"
              >
                <el-option 
                  v-for="hour in availableHours" 
                  :key="hour" 
                  :label="`${hour}:00`" 
                  :value="hour" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
 
        <!-- 价格信息 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单价 (¥)" prop="unitPrice">
              <el-input 
                v-model="form.unitPrice"   
                :disabled="true" 
                style="width: 100%"
              >
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="数量" prop="quantity">
              <el-input-number 
                v-model="form.quantity"  
                :min="1"
                :max="999"
                style="width: 100%"
                @change="calculateTotal"
              />
            </el-form-item>

          </el-col>
          <el-col :span="8">
            <el-form-item label="总金额 (¥)">
              <el-input 
                v-model="form.totalAmount"   
                :disabled="true" 
                style="width: 100%"
              >
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
 
        <!-- 备注信息：修复校验规则中的空格问题 -->
        <el-form-item 
          label="产品用途、备注等其它需求：1. 承载货物描述：（必填）；2. 接受产品细节调剂的方面：（可联系厂家进行单价优惠）；3. 其它："
          prop="remark"
        >
          <el-input 
            v-model="form.remark"   
            type="textarea" 
            :rows="6" 
            placeholder="请输入备注信息" 
            maxlength="500"
            show-word-limit 
          />
        </el-form-item>
 
        <!-- 图片上传 -->
        <el-form-item label="图片备注">
          <el-upload 
            v-model:file-list="form.images"   
            action="/api/upload" 
            list-type="picture-card" 
            :limit="3"
            :on-exceed="handleExceed" 
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess" 
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
 
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitProduct">
            提交产品配置 
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
 
    <!-- 订单确认弹窗：保持不变 -->
    <el-dialog 
      v-model="showConfirmDialog"
      title="订单确认"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentProduct">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="产品名称">
            {{ currentProduct.name }}
          </el-descriptions-item>
          <el-descriptions-item label="产品类型">
            {{ currentProduct.sidefork === 0 ? '二面叉' : '四面叉' }}
          </el-descriptions-item>
          <el-descriptions-item label="面板类型">
            {{ currentProduct.panel_leg === 0 ? '板条-原木' : '胶合板-多层板' }}
          </el-descriptions-item>
          <el-descriptions-item label="生产类型">
            {{ currentProduct.customize === 0 ? '二手' : '定制' }}
          </el-descriptions-item>
          <el-descriptions-item label="单价">
            ¥{{ form.unitPrice }}
          </el-descriptions-item>
          <el-descriptions-item label="数量">
            {{ form.quantity }}
          </el-descriptions-item>
        </el-descriptions>
        <div class="price-summary">
          <h3>总金额：¥{{ form.totalAmount }}</h3>
        </div>
      </div>
      <template #footer>
        <p style="font-size: 12px; color: #bbb; position: relative;left: -280px;">期望时间仅供参考，但我们会保障质量的情况下尽力办到</p>
        <p style="font-size: 12px; color: #bbb; position: relative;left: -310px;">如若特殊情况请联系：18068471547，进行优先协调</p>
        <el-button @click="showConfirmDialog = false">返回修改</el-button>
        <el-button type="primary" @click="confirmOrder">确认订单</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 


<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { product_addAPI, order_addAPI } from '@/api/api'
import authStore from '@/model/authstore' 
import PalletSimulator from '@/components/PalletSimulator/index.vue' 

// 常量定义 
const availableHours = Array.from({ length: 12 }, (_, i) => i + 7) // 7:00-18:00 

// 引用声明 
const palletSimulator = ref(null)
const orderFormRef = ref(null)
const showConfirmDialog = ref(false)
const currentProduct = ref(null)

// 表单数据 
const form = reactive({
  deliveryDate: '',
  deliveryHour: '',
  remark: '1.\n2.\n3.\n...',
  images: [],
  quantity: 1,
  unitPrice: 0,
  totalAmount: 0,
  palletConfig: {} // 初始为空对象
})
let lastValidationError = ''
// 表单验证规则 
const rules = {
  deliveryDate: [
    { required: true, message: '请选择送货日期', trigger: 'blur' }
  ],
  deliveryHour: [
    { required: true, message: '请选择送货时间', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '数量需在1-999之间', trigger: 'blur' }
  ]
  ,
  remark: [
  { 
    required: true,
    trigger: 'blur',
    validator: (_, value, callback) => {
      if (!value || value.trim() === '') {
        lastValidationError = '请填写备注信息'
        callback(new Error(lastValidationError))
        return
      }
      
      const index1 = value.indexOf('1.')
      const index2 = value.indexOf('2.')
      
      if (index1 === -1 || index2 === -1 || index1 >= index2) {
        lastValidationError = '请按正确格式填写：1.用途描述 2.调剂方面'
        callback(new Error(lastValidationError))
        return
      }
      
      const contentBetween = value.substring(index1 + 2, index2).trim()
      
      if (contentBetween.length < 2) {
        lastValidationError = '请输入用途描述，不少于2字'
        callback(new Error(lastValidationError))
      } else {
        lastValidationError = '' // 清空错误
        callback()
      }
    }
  }
]

}

// 计算总金额 
const calculateTotal = () => {
  form.totalAmount = (parseFloat(form.unitPrice || 0) * (form.quantity || 1)).toFixed(2)
}

// 监听3D模拟器配置变化
const handlePalletUpdate = (newConfig) => {
  form.palletConfig = { ...newConfig }
}

// 🔥 修复：获取当前产品配置
const getCurrentPalletConfig = () => {
  if (!palletSimulator.value) {
    return null
  }
  try {
    const config = palletSimulator.value.getFullConfig()
    return config
  } catch (error) {
    return null
  }
}

// 🔥 修复：测试方法，验证配置获取
const testGetConfig = () => {
  const config = getCurrentPalletConfig()
  if (config) {
    ElMessage.success('配置获取成功，请查看控制台')
  } else {
    ElMessage.error('配置获取失败')
  }
}


//// 提交产品配置 - 使用实时配置
const submitProduct = async () => {
  try {
    // 表单验证 
   await orderFormRef.value.validate() 
    
    // 🔥 关键修复：实时获取最新配置，而不是使用缓存的form.palletConfig
    const cfg = getCurrentPalletConfig()
    if (!cfg) {
      ElMessage.error('无法获取产品配置，请检查3D模拟器')
      return
    }
    
    // 构建产品数据（严格匹配数据库字段）
    const productData = {
      name: `${cfg.boardLength}*${cfg.beamLength}`, 
      sidefork: cfg.palletType === 'two' ? 0 : 1,
      panel_leg: cfg.panelType === 'wooden' ? 0 : 1,
      customize: cfg.productionType === 'custom' ? 1 : 0,
      t_bottomlayer: cfg.bottomType === 'support' ? 1 : 0,
      t_leglayout: cfg.palletType  === 'two' ? 
            (cfg.productionType  === 'custom' ? 
            (cfg.beamLayout  === 'three' ? 1 : 2) : 0) : 0, // 四面叉强制为0 
      tf_boardwing: cfg.wingWidth, 
      f_structure: cfg.legStructure.replace('type', '').toUpperCase(),
      f_blockheight: cfg.useCustomHeight ? cfg.blockHeight : 0,

    }
    console.log('productData:',productData)
    // API调用 
    const res = await product_addAPI(productData)
    if (!res?.data?.pid) throw new Error('获取产品ID失败')

    // 更新状态 
    currentProduct.value = { 
      ...productData, 
      pid: res.data.pid, 
      name: productData.name, 
      price: res.data.price  
    }
    form.unitPrice = res.data.price.toFixed(2) 
    calculateTotal()
    showConfirmDialog.value = true 

  } catch (err) {
    const errorMessage = lastValidationError || 
                        err.response?.data?.message || 
                        err.message || 
                        'error'
    ElMessage.error(`提交失败: ${errorMessage}`)
  }
}
 

//Order
// ///////////////////////////////确认订单提交 
const confirmOrder = async () => {
  try {
    const authData = authStore.get('auth') 

    // 验证登录状态 
    if (!authStore.isAuthenticated) throw new Error('请先登录')
 
    // 验证产品信息 
    if (!currentProduct.value?.pid) throw new Error('无效的产品配置')
    const eta = new Date(form.deliveryDate); 
    eta.setHours(form.deliveryHour,  0, 0, 0);
    // 构建订单数据 
    const orderData = {
      pid: currentProduct.value.pid, 
      cid: authData.user?.cid,
      eta:eta.toISOString(), 
      quantity: form.quantity, 
      price: parseFloat(form.unitPrice), 
      total_amount: parseFloat(form.totalAmount), 
      remark: form.remark, 
      images: form.images  
        .map(img => img.response?.data?.url || img.url) 
        .filter(url => url && url.trim() !== '')
        .join(','),
      status: 0 // 0=待确认 
    }

    
    // API调用 
    await order_addAPI(orderData)
    ElMessage.success('订单创建成功!')
    resetForm()

  } catch (err) {

    ElMessage.error(`下单失败: ${err.response?.data?.message || err.message}`) 
  } finally {
    showConfirmDialog.value = false 
  }
}

// 辅助函数：日期格式化 
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return [
    d.getFullYear(), 
    String(d.getMonth() + 1).padStart(2, '0'),
    String(d.getDate()).padStart(2, '0')
  ].join('')
}

// 禁用过去的日期 
const disabledPastDates = (time) => {
  return time.getTime() < Date.now() - 86400000 // 86400000ms = 1天 
}

// 重置表单 
const resetForm = () => {
  orderFormRef.value?.resetFields() 
  form.quantity = 1 
  form.unitPrice = 0 
  form.totalAmount = 0 
  form.images = []
  palletSimulator.value?.reset?.() 
}

// 图片上传处理 
const handleExceed = () => ElMessage.warning('最多上传3张图片')
const beforeUpload = (file) => {
  const isValid = file.type.startsWith('image/') && file.size / 1024 / 1024 < 5 
  if (!isValid) ElMessage.error('请上传小于5MB的图片文件')
  return isValid 
}
const handleUploadSuccess = (res, file) => {
  file.url = res.data?.url || ''
}

// 监听器 
watch(() => form.quantity, calculateTotal)
watch(() => form.unitPrice, calculateTotal)

// 🔥 暴露方法给模板
defineExpose({
  testGetConfig
})
</script>
 




<style scoped>
/* 样式保持不变，优化细节 */
.order-form-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
 
.pallet-card,
.form-card {
  padding: 20px;
  background: #fff;
}
 
.card-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
  padding-bottom: 10px;
}
 
.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
 
.el-form-item {
  margin-bottom: 18px;
}
 
.price-summary {
  margin-top: 20px;
  text-align: right;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}
 
/* 响应式优化 */
@media (max-width: 768px) {
  .order-form-container {
    padding: 10px;
  }
  .el-row {
    flex-direction: column;
  }
  .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>